﻿using Model.DocumentDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Studio.DocumentDB
{
    /// <summary>List connected DocDB accounts and their hierarchy.</summary>
    public partial class AccountListControl : UserControl
    {
        /// <summary>Constructor.</summary>
        public AccountListControl()
        {
            InitializeComponent();
        }

        private async void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var treeView = sender as TreeView;
            var studio = DataContext as StudioViewModel;
            var folder = treeView.SelectedValue as FolderViewModel;

            if(studio!=null)
            {   //  Propagates selection
                studio.Accounts.SelectedValue = treeView.SelectedValue;
            }
            if (folder != null)
            {
                try
                {
                    await folder.EnsureLoadedAsync();
                }
                catch (Exception ex)
                {
                    var message = "Error while reading the databases."
                        + Environment.NewLine
                        + ex.Message;
                    var parentWindow = Window.GetWindow(this);

                    MessageBox.Show(parentWindow, message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }
        }
    }
}
